package com.example.networkcore.retrofit;

import com.example.networkcore.protocol.BaseRespEntity;
import com.example.networkcore.protocol.TokenRespEntity;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomGsonResponseBodyConverter(Type _type,Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
        this.type=_type;
    }

    private Type type;


    @Override public T convert(ResponseBody value) throws IOException {

        String string = value.string();

        if(string.toLowerCase().contains("access_token")){
            return (T) new Gson().fromJson(string, TokenRespEntity.class);
        }

        BaseRespEntity baseRespEntity = gson.fromJson(string, BaseRespEntity.class);
        if (baseRespEntity.getCode()!=200){
            return (T) baseRespEntity;
        }else{
            return gson.fromJson(string,type);
        }

    }
}
